package org.android.bbdroid.gui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.android.bbdroid.guiutils.HTMLUtils;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class BBDroidForumAdapter extends BaseAdapter
{
  private String categoryDesc;
  private String categoryName;
  private ArrayList<Map<String, Object>> data;
  private String dataDesc;
  private String dataName;
  private LayoutInflater inflater;

  public BBDroidForumAdapter(Context c, List<Map<String, Object>> groupData, String categoryName, String categoryDesc, List<List<Map<String, Object>>> childData, String dataName, String dataDesc)
  {
    this.inflater = LayoutInflater.from(c);
    this.categoryName = categoryName;
    this.categoryDesc = categoryDesc;
    this.dataName = dataName;
    this.dataDesc = dataDesc;
    data=new ArrayList<Map<String,Object>>();
    Iterator<List<Map<String,Object>>> it=childData.iterator();
    for(Map<String,Object> group: groupData){
    	List<Map<String,Object>> children=it.next();
    	data.add(group);
    	for(Map<String,Object> child: children)
    		data.add(child);
    }
  }

  public int getCount()
  {
    return this.data.size();
  }

  public Object getItem(int position)
  {
    return this.data.get(position);
  }

  public long getItemId(int position)
  {
    return this.data.get(position).hashCode();
  }

  public View getView(int position, View v, ViewGroup vg)
  {
    Map<String,Object> data = this.data.get(position);
    View view = v;
    if (data.containsKey(this.categoryName))
    {
      if (view == null)
        view = this.inflater.inflate(org.android.bbdroid.R.layout.forum_group, null);
      
      ((TextView)view.findViewById(org.android.bbdroid.R.id.tvCategoryName)).setText(HTMLUtils.fromHTML((String)data.get(this.categoryName)));
      ((TextView)view.findViewById(org.android.bbdroid.R.id.tvCategoryDescription)).setText(HTMLUtils.fromHTML((String)data.get(this.categoryDesc)));
    }else{
        if (view == null)
            view = this.inflater.inflate(org.android.bbdroid.R.layout.forum_child, null);
        
        ((TextView)view.findViewById(org.android.bbdroid.R.id.tvChildN)).setText(HTMLUtils.fromHTML((String)data.get(this.dataName)));
        ((TextView)view.findViewById(org.android.bbdroid.R.id.tvChildD)).setText(HTMLUtils.fromHTML((String)data.get(this.dataDesc)));
        if (position % 2 == 0)
          view.setBackgroundResource(org.android.bbdroid.R.color.child_background);
        else
        	view.setBackgroundResource(org.android.bbdroid.R.color.child_background_lighter);
    }
    
    return view;
  }
}